<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                <el-form-item label="名称" prop="name">
                      <el-input
                          v-model="queryParams.name"
                          placeholder="名称"
                          clearable
                          @keyup.enter="handleQuery()"
                      />
                </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button
            type="success"
            @click="handleOpenDialog()"
        >
          <template #icon><Plus /></template>
          新增
        </el-button>
        <el-button
            type="danger"
            :disabled="removeIds.length === 0"
            @click="handleDelete()"
        >
          <template #icon><Delete /></template>
          删除
        </el-button>
      </div>

      <el-table
          ref="dataTableRef"
          v-loading="loading"
          :data="pageData"
          highlight-current-row
          border
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
                <el-table-column
                    key="name"
                    label="名称"
                    prop="name"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="firstCode"
                    label="一级分类编码"
                    prop="firstCode"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="secondCode"
                    label="二级分类编码"
                    prop="secondCode"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="ediblePortion"
                    label="食部(%)"
                    prop="ediblePortion"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="water"
                    label="水分(g)"
                    prop="water"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="energyKcal"
                    label="能量（千卡）"
                    prop="energyKcal"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="energyKj"
                    label="能量（千焦）"
                    prop="energyKj"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="protein"
                    label="蛋白质(g)"
                    prop="protein"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="fat"
                    label="脂肪(g)"
                    prop="fat"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="carbohydrate"
                    label="碳水化物(g)"
                    prop="carbohydrate"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="fiber"
                    label="膳食纤维(g)"
                    prop="fiber"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="cholesterol"
                    label="胆固醇(mg)"
                    prop="cholesterol"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="ash"
                    label="灰分(g)"
                    prop="ash"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="vitaminA"
                    label="维生素A(μgRE)"
                    prop="vitaminA"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="thiamine"
                    label="硫胺素(mg)"
                    prop="thiamine"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="riboflavin"
                    label="核黄素(mg)"
                    prop="riboflavin"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="vitaminB6"
                    label="维生素B6(mg)"
                    prop="vitaminB6"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="vitaminB12"
                    label="维生素B12(mg)"
                    prop="vitaminB12"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="folate"
                    label="叶酸(ug)"
                    prop="folate"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="niacin"
                    label="烟碱(mg)"
                    prop="niacin"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="vitaminC"
                    label="维生素C(mg)"
                    prop="vitaminC"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="vitaminE"
                    label="维生素E(mg)"
                    prop="vitaminE"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="calcium"
                    label="钙(mg)"
                    prop="calcium"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="phosphorus"
                    label="磷(mg)"
                    prop="phosphorus"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="potassium"
                    label="钾(mg)"
                    prop="potassium"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="sodium"
                    label="钠(mg)"
                    prop="sodium"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="magnesium"
                    label="镁(mg)"
                    prop="magnesium"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="iron"
                    label="铁(mg)"
                    prop="iron"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="zinc"
                    label="锌(mg)"
                    prop="zinc"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="selenium"
                    label="硒(mg)"
                    prop="selenium"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="copper"
                    label="铜(mg)"
                    prop="copper"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="manganese"
                    label="锰(mg)"
                    prop="manganese"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="lodine"
                    label="碘(mg)"
                    prop="lodine"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="carotene"
                    label="胡萝卜素(μg)"
                    prop="carotene"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="retinol"
                    label="视黄醇(μg)"
                    prop="retinol"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="niacinOrNiacin"
                    label="尼克酸/烟酸(mg)"
                    prop="niacinOrNiacin"
                    min-width="150"
                    align="center"
                />
                <el-table-column
                    key="αTocopherol"
                    label="α-维生素E(mg)"
                    prop="αTocopherol"
                    min-width="150"
                    align="center"
                />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
                type="primary"
                size="small"
                link
                @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon><Edit /></template>
              编辑
            </el-button>
            <el-button
                type="danger"
                size="small"
                link
                @click="handleDelete(scope.row.id)"
            >
              <template #icon><Delete /></template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handleQuery()"
      />
    </el-card>

    <!-- 食物数据表单弹窗 -->
    <el-dialog
        v-model="dialog.visible"
        :title="dialog.title"
        width="500px"
        @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
                <el-form-item label="" prop="id">
                      <el-input
                          v-model="formData.id"
                          placeholder=""
                      />
                </el-form-item>
                <el-form-item label="名称" prop="name">
                      <el-input
                          v-model="formData.name"
                          placeholder="名称"
                      />
                </el-form-item>
                <el-form-item label="一级分类编码" prop="firstCode">
                      <el-input
                          v-model="formData.firstCode"
                          placeholder="一级分类编码"
                      />
                </el-form-item>
                <el-form-item label="二级分类编码" prop="secondCode">
                      <el-input
                          v-model="formData.secondCode"
                          placeholder="二级分类编码"
                      />
                </el-form-item>
                <el-form-item label="食部(%)" prop="ediblePortion">
                      <el-input
                          v-model="formData.ediblePortion"
                          placeholder="食部(%)"
                      />
                </el-form-item>
                <el-form-item label="水分(g)" prop="water">
                      <el-input
                          v-model="formData.water"
                          placeholder="水分(g)"
                      />
                </el-form-item>
                <el-form-item label="能量（千卡）" prop="energyKcal">
                      <el-input
                          v-model="formData.energyKcal"
                          placeholder="能量（千卡）"
                      />
                </el-form-item>
                <el-form-item label="能量（千焦）" prop="energyKj">
                      <el-input
                          v-model="formData.energyKj"
                          placeholder="能量（千焦）"
                      />
                </el-form-item>
                <el-form-item label="蛋白质(g)" prop="protein">
                      <el-input
                          v-model="formData.protein"
                          placeholder="蛋白质(g)"
                      />
                </el-form-item>
                <el-form-item label="脂肪(g)" prop="fat">
                      <el-input
                          v-model="formData.fat"
                          placeholder="脂肪(g)"
                      />
                </el-form-item>
                <el-form-item label="碳水化物(g)" prop="carbohydrate">
                      <el-input
                          v-model="formData.carbohydrate"
                          placeholder="碳水化物(g)"
                      />
                </el-form-item>
                <el-form-item label="膳食纤维(g)" prop="fiber">
                      <el-input
                          v-model="formData.fiber"
                          placeholder="膳食纤维(g)"
                      />
                </el-form-item>
                <el-form-item label="胆固醇(mg)" prop="cholesterol">
                      <el-input
                          v-model="formData.cholesterol"
                          placeholder="胆固醇(mg)"
                      />
                </el-form-item>
                <el-form-item label="灰分(g)" prop="ash">
                      <el-input
                          v-model="formData.ash"
                          placeholder="灰分(g)"
                      />
                </el-form-item>
                <el-form-item label="维生素A(μgRE)" prop="vitaminA">
                      <el-input
                          v-model="formData.vitaminA"
                          placeholder="维生素A(μgRE)"
                      />
                </el-form-item>
                <el-form-item label="硫胺素(mg)" prop="thiamine">
                      <el-input
                          v-model="formData.thiamine"
                          placeholder="硫胺素(mg)"
                      />
                </el-form-item>
                <el-form-item label="核黄素(mg)" prop="riboflavin">
                      <el-input
                          v-model="formData.riboflavin"
                          placeholder="核黄素(mg)"
                      />
                </el-form-item>
                <el-form-item label="维生素B6(mg)" prop="vitaminB6">
                      <el-input
                          v-model="formData.vitaminB6"
                          placeholder="维生素B6(mg)"
                      />
                </el-form-item>
                <el-form-item label="维生素B12(mg)" prop="vitaminB12">
                      <el-input
                          v-model="formData.vitaminB12"
                          placeholder="维生素B12(mg)"
                      />
                </el-form-item>
                <el-form-item label="叶酸(ug)" prop="folate">
                      <el-input
                          v-model="formData.folate"
                          placeholder="叶酸(ug)"
                      />
                </el-form-item>
                <el-form-item label="烟碱(mg)" prop="niacin">
                      <el-input
                          v-model="formData.niacin"
                          placeholder="烟碱(mg)"
                      />
                </el-form-item>
                <el-form-item label="维生素C(mg)" prop="vitaminC">
                      <el-input
                          v-model="formData.vitaminC"
                          placeholder="维生素C(mg)"
                      />
                </el-form-item>
                <el-form-item label="维生素E(mg)" prop="vitaminE">
                      <el-input
                          v-model="formData.vitaminE"
                          placeholder="维生素E(mg)"
                      />
                </el-form-item>
                <el-form-item label="钙(mg)" prop="calcium">
                      <el-input
                          v-model="formData.calcium"
                          placeholder="钙(mg)"
                      />
                </el-form-item>
                <el-form-item label="磷(mg)" prop="phosphorus">
                      <el-input
                          v-model="formData.phosphorus"
                          placeholder="磷(mg)"
                      />
                </el-form-item>
                <el-form-item label="钾(mg)" prop="potassium">
                      <el-input
                          v-model="formData.potassium"
                          placeholder="钾(mg)"
                      />
                </el-form-item>
                <el-form-item label="钠(mg)" prop="sodium">
                      <el-input
                          v-model="formData.sodium"
                          placeholder="钠(mg)"
                      />
                </el-form-item>
                <el-form-item label="镁(mg)" prop="magnesium">
                      <el-input
                          v-model="formData.magnesium"
                          placeholder="镁(mg)"
                      />
                </el-form-item>
                <el-form-item label="铁(mg)" prop="iron">
                      <el-input
                          v-model="formData.iron"
                          placeholder="铁(mg)"
                      />
                </el-form-item>
                <el-form-item label="锌(mg)" prop="zinc">
                      <el-input
                          v-model="formData.zinc"
                          placeholder="锌(mg)"
                      />
                </el-form-item>
                <el-form-item label="硒(mg)" prop="selenium">
                      <el-input
                          v-model="formData.selenium"
                          placeholder="硒(mg)"
                      />
                </el-form-item>
                <el-form-item label="铜(mg)" prop="copper">
                      <el-input
                          v-model="formData.copper"
                          placeholder="铜(mg)"
                      />
                </el-form-item>
                <el-form-item label="锰(mg)" prop="manganese">
                      <el-input
                          v-model="formData.manganese"
                          placeholder="锰(mg)"
                      />
                </el-form-item>
                <el-form-item label="碘(mg)" prop="lodine">
                      <el-input
                          v-model="formData.lodine"
                          placeholder="碘(mg)"
                      />
                </el-form-item>
                <el-form-item label="胡萝卜素(μg)" prop="carotene">
                      <el-input
                          v-model="formData.carotene"
                          placeholder="胡萝卜素(μg)"
                      />
                </el-form-item>
                <el-form-item label="视黄醇(μg)" prop="retinol">
                      <el-input
                          v-model="formData.retinol"
                          placeholder="视黄醇(μg)"
                      />
                </el-form-item>
                <el-form-item label="尼克酸/烟酸(mg)" prop="niacinOrNiacin">
                      <el-input
                          v-model="formData.niacinOrNiacin"
                          placeholder="尼克酸/烟酸(mg)"
                      />
                </el-form-item>
                <el-form-item label="α-维生素E(mg)" prop="αTocopherol">
                      <el-input
                          v-model="formData.αTocopherol"
                          placeholder="α-维生素E(mg)"
                      />
                </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  defineOptions({
    name: "FoodInfo",
    inheritAttrs: false,
  });

  import FoodInfoAPI, { FoodInfoPageVO, FoodInfoForm, FoodInfoPageQuery } from "@/api/food/food-info";

  const queryFormRef = ref(ElForm);
  const dataFormRef = ref(ElForm);

  const loading = ref(false);
  const removeIds = ref<number[]>([]);
  const total = ref(0);

  const queryParams = reactive<FoodInfoPageQuery>({
    pageNum: 1,
    pageSize: 10,
  });

  // 食物数据表格数据
  const pageData = ref<FoodInfoPageVO[]>([]);

  // 弹窗
  const dialog = reactive({
    title: "",
    visible: false,
  });

  // 食物数据表单数据
  const formData = reactive<FoodInfoForm>({});

  // 食物数据表单校验规则
  const rules = reactive({
                      name: [{ required: true, message: "请输入名称", trigger: "blur" }],
                      firstCode: [{ required: true, message: "请输入一级分类编码", trigger: "blur" }],
                      secondCode: [{ required: true, message: "请输入二级分类编码", trigger: "blur" }],
                      ediblePortion: [{ required: true, message: "请输入食部(%)", trigger: "blur" }],
                      water: [{ required: true, message: "请输入水分(g)", trigger: "blur" }],
                      energyKcal: [{ required: true, message: "请输入能量（千卡）", trigger: "blur" }],
                      energyKj: [{ required: true, message: "请输入能量（千焦）", trigger: "blur" }],
                      protein: [{ required: true, message: "请输入蛋白质(g)", trigger: "blur" }],
                      fat: [{ required: true, message: "请输入脂肪(g)", trigger: "blur" }],
                      carbohydrate: [{ required: true, message: "请输入碳水化物(g)", trigger: "blur" }],
                      fiber: [{ required: true, message: "请输入膳食纤维(g)", trigger: "blur" }],
                      cholesterol: [{ required: true, message: "请输入胆固醇(mg)", trigger: "blur" }],
                      ash: [{ required: true, message: "请输入灰分(g)", trigger: "blur" }],
                      vitaminA: [{ required: true, message: "请输入维生素A(μgRE)", trigger: "blur" }],
                      thiamine: [{ required: true, message: "请输入硫胺素(mg)", trigger: "blur" }],
                      riboflavin: [{ required: true, message: "请输入核黄素(mg)", trigger: "blur" }],
                      vitaminB6: [{ required: true, message: "请输入维生素B6(mg)", trigger: "blur" }],
                      vitaminB12: [{ required: true, message: "请输入维生素B12(mg)", trigger: "blur" }],
                      folate: [{ required: true, message: "请输入叶酸(ug)", trigger: "blur" }],
                      niacin: [{ required: true, message: "请输入烟碱(mg)", trigger: "blur" }],
                      vitaminC: [{ required: true, message: "请输入维生素C(mg)", trigger: "blur" }],
                      vitaminE: [{ required: true, message: "请输入维生素E(mg)", trigger: "blur" }],
                      calcium: [{ required: true, message: "请输入钙(mg)", trigger: "blur" }],
                      phosphorus: [{ required: true, message: "请输入磷(mg)", trigger: "blur" }],
                      potassium: [{ required: true, message: "请输入钾(mg)", trigger: "blur" }],
                      sodium: [{ required: true, message: "请输入钠(mg)", trigger: "blur" }],
                      magnesium: [{ required: true, message: "请输入镁(mg)", trigger: "blur" }],
                      iron: [{ required: true, message: "请输入铁(mg)", trigger: "blur" }],
                      zinc: [{ required: true, message: "请输入锌(mg)", trigger: "blur" }],
                      selenium: [{ required: true, message: "请输入硒(mg)", trigger: "blur" }],
                      copper: [{ required: true, message: "请输入铜(mg)", trigger: "blur" }],
                      manganese: [{ required: true, message: "请输入锰(mg)", trigger: "blur" }],
                      lodine: [{ required: true, message: "请输入碘(mg)", trigger: "blur" }],
                      carotene: [{ required: true, message: "请输入胡萝卜素(μg)", trigger: "blur" }],
                      retinol: [{ required: true, message: "请输入视黄醇(μg)", trigger: "blur" }],
                      niacinOrNiacin: [{ required: true, message: "请输入尼克酸/烟酸(mg)", trigger: "blur" }],
                      αTocopherol: [{ required: true, message: "请输入α-维生素E(mg)", trigger: "blur" }],
  });

  /** 查询食物数据 */
  function handleQuery() {
    loading.value = true;
          FoodInfoAPI.getPage(queryParams)
        .then((data) => {
          pageData.value = data.list;
          total.value = data.total;
        })
        .finally(() => {
          loading.value = false;
        });
  }

  /** 重置食物数据查询 */
  function handleResetQuery() {
    queryFormRef.value!.resetFields();
    queryParams.pageNum = 1;
    handleQuery();
  }

  /** 行复选框选中记录选中ID集合 */
  function handleSelectionChange(selection: any) {
    removeIds.value = selection.map((item: any) => item.id);
  }

  /** 打开食物数据弹窗 */
  function handleOpenDialog(id?: number) {
    dialog.visible = true;
    if (id) {
      dialog.title = "修改食物数据";
            FoodInfoAPI.getFormData(id).then((data) => {
        Object.assign(formData, data);
      });
    } else {
      dialog.title = "新增食物数据";
    }
  }

  /** 提交食物数据表单 */
  function handleSubmit() {
    dataFormRef.value.validate((valid: any) => {
      if (valid) {
        loading.value = true;
        const id = formData.id;
        if (id) {
                FoodInfoAPI.update(id, formData)
              .then(() => {
                ElMessage.success("修改成功");
                handleCloseDialog();
                handleResetQuery();
              })
              .finally(() => (loading.value = false));
        } else {
                FoodInfoAPI.add(formData)
              .then(() => {
                ElMessage.success("新增成功");
                handleCloseDialog();
                handleResetQuery();
              })
              .finally(() => (loading.value = false));
        }
      }
    });
  }

  /** 关闭食物数据弹窗 */
  function handleCloseDialog() {
    dialog.visible = false;
    dataFormRef.value.resetFields();
    dataFormRef.value.clearValidate();
    formData.id = undefined;
  }

  /** 删除食物数据 */
  function handleDelete(id?: number) {
    const ids = [id || removeIds.value].join(",");
    if (!ids) {
      ElMessage.warning("请勾选删除项");
      return;
    }

    ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(
        () => {
          loading.value = true;
                FoodInfoAPI.deleteByIds(ids)
              .then(() => {
                ElMessage.success("删除成功");
                handleResetQuery();
              })
              .finally(() => (loading.value = false));
        },
        () => {
          ElMessage.info("已取消删除");
        }
    );
  }

  onMounted(() => {
    handleQuery();
  });
</script>
